//
//  ByUIBuyCarSafetyVC.m
//  chequanbao_ios
//
//  Created by pro on 17/5/9.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIBuyCarSafetyVC.h"

// view
#import "ByViewBuySafetyCardSelect.h"

// api
#import "ByApiSafety.h"


@interface ByUIBuyCarSafetyVC ()
@property (nonatomic, strong) NSMutableArray<UITextField *> *textFields;
@property (nonatomic, strong) NSMutableArray *selectViews;
@property (nonatomic, strong) UIScrollView *scroll;

@property (nonatomic, strong) ByIconChooseDataSource *imageDatasource;

@property (nonatomic, strong) NSArray *infoAry;
@property (nonatomic, strong) NSMutableArray *infoSelect;        // 车险拼接
@property (nonatomic, strong) UIButton *submitBtn;
@end

@implementation ByUIBuyCarSafetyVC
{
    NSInteger _selectedIndex;     // 选中的50玩，100万，还是150万
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"车辆信息";
    self.view.backgroundColor = [UIColor blueColor];
    
    [self addLeftBackBarButtonItem];
    
    [self createViews];
}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    self.scroll.top = self.view.safeAreaInsets.top;
    self.scroll.height = self.view.height - self.view.safeAreaInsets.bottom - self.view.safeAreaInsets.top - 40;
//    UIButton *submitButton = [self.view viewWithTag:100];
    _submitBtn.bottom = self.view.height - self.view.safeAreaInsets.bottom;
//    submitButton.y = 100;
//    submitButton.width = 200;
//    submitButton.height = 50;
    
}

#pragma mark - 懒加载
- (NSMutableArray *)textFields {
    
    if (!_textFields) {
        _textFields = [[NSMutableArray alloc] init];
    }
    return _textFields;
}
- (NSMutableArray *)selectViews {
    
    if (!_selectViews) {
        _selectViews = [[NSMutableArray alloc] init];
    }
    return _selectViews;
}
- (ByIconChooseDataSource *)imageDatasource {
    
    if (!_imageDatasource) {
        _imageDatasource = [[ByIconChooseDataSource alloc] init];
        [_imageDatasource fireWithViewController:self];
    }
    return _imageDatasource;
}

- (UIScrollView *)scroll {
    
    if (!_scroll) {
        _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 40)];
        _scroll.showsVerticalScrollIndicator = NO;
        _scroll.bounces = NO;
        [self.view addSubview:_scroll];
    }
    return _scroll;
}

- (NSArray *)infoAry{
    if (!_infoAry) {
        _infoAry =  @[@"机动车损失保险",@"不计免赔险",@"机动车车身划痕险",@"车上人员险（包括司机和乘客）",@"机动车全车盗抢险",@"玻璃单独破碎险",@"自燃损失险",@"发动机涉水损失险(两年以内可承保)",@"机动车损失保险无法找到第三方特约险(三年以内可承保)"];
    }
    return _infoAry;
}

- (NSMutableArray *)infoSelect{
    if (!_infoSelect) {
        _infoSelect = [NSMutableArray array];
    }
    return _infoSelect;
}
#pragma mark - 创建视图
- (void)createViews {
    
    CGFloat x, y, width, height;
    
    x = 10;
    y = 0;
    width = SCREEN_WIDTH - x * 2;
    height = 0;
    /*
     车主信息
     */
    UIView *infoBgView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [self.scroll addSubview:infoBgView];
    infoBgView.layer.cornerRadius = 4;
    infoBgView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.2];
    
    CGFloat offsetY = 15;
    NSArray *infoTitles = @[@"车主姓名：", @"车牌号码：", @"手机号码："];
    for (int i = 0; i < infoTitles.count; i ++) {
        
        x = 15;
        y = 0;
        width = [infoTitles[i] getSizeOfString:16].width + 2;
        height = 20;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        label.adjustsFontSizeToFitWidth = YES;
        label.font = FONT(15);
        label.text = infoTitles[i];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentLeft;
        [infoBgView addSubview:label];
        
        x = label.right;
        y = offsetY;
        width = infoBgView.width - 15 - x;
        height = 35;
        UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(x, y, width, height)];
        tf.textColor = [UIColor whiteColor];
        tf.layer.borderColor = [UIColor whiteColor].CGColor;
        tf.layer.borderWidth = 1;
        tf.layer.cornerRadius = 2;
        [infoBgView addSubview:tf];
        
        [self.textFields addObject:tf];
        
        label.y = tf.y;
        
        offsetY = tf.bottom + 15;
        
        if (i == infoTitles.count - 1) {
            tf.keyboardType = UIKeyboardTypePhonePad;
        }
        
    }
    
    infoBgView.height = infoBgView.subviews.lastObject.bottom + 15;
    
    
    /*
     上传按钮
     */
    width = SCREEN_WIDTH;
    height = 40;
    x = 0;
    y = SCREEN_HEIGHT - height;
    _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _submitBtn.backgroundColor = BY_THEME_COLOR;
    [_submitBtn setFrame:CGRectMake(x, y, width, height)];
    [_submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [_submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_submitBtn addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    _submitBtn.tag = 100;
    [self.view addSubview:_submitBtn];
    
    /*
     证件照
     */
    NSArray *titles = @[@"上传身份证正面",
                        @"上传身份证反面",
                        @"上传行驶证正面",
                        @"上传行驶证反面",
                        @"上传年检证明",
                        @"上传历史车险信息"];
    for (int i = 0; i < titles.count; i ++) {
        
        width = (self.scroll.width - 10 * 3) / 2;
//        height = (submitBtn.top - infoBgView.bottom - 10 * 4) / 3;
        height = width * 2 / 3;
        x = 10 + i % 2 * (width + 10);
        y = infoBgView.bottom + 10 + i / 2 * (height + 10);
        ByViewBuySafetyCardSelect *view = [[ByViewBuySafetyCardSelect alloc] initWithFrame:CGRectMake(x, y, width, height)];
        view.placeholder.image = [UIImage imageNamed:[NSString stringWithFormat:@"Safty_placeholder_%i", i + 1]];
        view.label.text = titles[i];
        [self.scroll addSubview:view];
        
        [self.selectViews addObject:view];
    }
    
    
    /*
     第三方责任险
     */
    UIView *lastCardView = self.scroll.subviews.lastObject;
    x = 10;
    y = lastCardView.bottom + 10;
    width = self.view.width - 20;
    height = 70;
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 4.0;
    [self.scroll addSubview:bgView];
    
    NSString *notes = @"第三方责任险";
    height = 20;
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, width, height)];
    noteLabel.numberOfLines = 0;
    noteLabel.font = FONT(14);
    noteLabel.text = notes;
    noteLabel.textColor = [UIColor blackColor];
    noteLabel.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:noteLabel];
    
    NSArray *noteTitles = @[@"50万", @"100万", @"150万"];
    width = [noteTitles[2] getSizeOfString:14].width + 10 + 20;
    CGFloat margin = (bgView.width - width * 3 - 20) / 2;
    for (int i = 0; i < noteTitles.count; i ++) {
        height = 20;
        x = 10 + (margin + width) * i;
        y = noteLabel.bottom + 10;
        UIControl *baseView = [[UIControl alloc] initWithFrame:CGRectMake(x, y, width, height)];
        baseView.tag = i + 1;
        [bgView addSubview:baseView];
        [baseView addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *selectView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        selectView.image = [UIImage imageNamed:@"Pay_unselected"];
        selectView.y = baseView.height / 2;
        [baseView addSubview:selectView];
        selectView.tag = 10;

        x = selectView.right;
        y = 0;

        height = baseView.height;
        CGFloat max_note_width = [noteTitles[2] getSizeOfString:14].width + 10;
        UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, max_note_width, height)];
        numberLabel.font = FONT(14);
        numberLabel.text = noteTitles[i];
        numberLabel.textColor = [UIColor blackColor];
        numberLabel.textAlignment = NSTextAlignmentLeft;
        [baseView addSubview:numberLabel];
        numberLabel.adjustsFontSizeToFitWidth = YES;
        numberLabel.tag = 20;
        
    }
//    UIView *lastCardView = self.scroll.subviews.lastObject;
//    x = lastCardView.right + 10;
//    y = lastCardView.top;
//    width = self.view.width - 10 - x;
//    height = lastCardView.height;
//    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
//    bgView.backgroundColor = [UIColor whiteColor];
//    bgView.layer.cornerRadius = 4.0;
//    [self.scroll addSubview:bgView];
//
//    NSString *notes = @"第三方责任险";
//    height = 20;
//    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, width, height)];
//    noteLabel.numberOfLines = 0;
//    noteLabel.font = FONT(14);
//    noteLabel.text = notes;
//    noteLabel.textColor = [UIColor blackColor];
//    noteLabel.textAlignment = NSTextAlignmentCenter;
//    [bgView addSubview:noteLabel];
//
//    NSArray *noteTitles = @[@"50万", @"100万", @"150万"];
//    for (int i = 0; i < noteTitles.count; i ++) {
//        width = noteLabel.width;
//        height = 20;
//        x = noteLabel.left;
//        y = noteLabel.bottom + height * i;
//        UIControl *baseView = [[UIControl alloc] initWithFrame:CGRectMake(x, y, width, height)];
//        baseView.tag = i + 1;
//        [bgView addSubview:baseView];
//        [baseView addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
//
//
//
////        x = 0;
//        y = 0;
//        width = 15;
//        height = 15;
//        CGFloat max_note_width = [noteTitles[2] getSizeOfString:14].width + 10;
//        x = (baseView.width - 15 - max_note_width - 10) / 2;
//        UIImageView *selectView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
//        selectView.image = [UIImage imageNamed:@"Pay_unselected"];
////        selectView.right = baseView.width / 2 - 5;
//        selectView.y = baseView.height / 2;
//        [baseView addSubview:selectView];
//        selectView.tag = 10;
//
//        x = selectView.right + 10;
//        y = 0;
////        width = baseView.width / 2;
//
//        height = baseView.height;
//        UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, max_note_width, height)];
//        numberLabel.font = FONT(14);
//        numberLabel.text = noteTitles[i];
//        numberLabel.textColor = [UIColor blackColor];
//        numberLabel.textAlignment = NSTextAlignmentLeft;
//        [baseView addSubview:numberLabel];
//        numberLabel.tag = 20;
//
//    }
    
    /*
     各种险
     */
    x = 10;
    y = bgView.bottom + 10;
    width = SCREEN_WIDTH - 20;
    margin = 10;
    height = self.infoAry.count * 30 + 10 + margin * (self.infoAry.count - 1); // 30（每种车险高） + 10（头尾间隔）+ (每行间隔)
    UIView *bgView2 = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    bgView2.backgroundColor = [UIColor whiteColor];
    bgView2.layer.cornerRadius = 4.0;
    [self.scroll addSubview:bgView2];
    for (int i = 0; i < self.infoAry.count; i ++) {
        y = 5 + i * (30 + margin);
        UIButton *selectedBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, y, 30, 30)];
        selectedBtn.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
        [selectedBtn setImage:[UIImage imageNamed:@"Safety_ubselected"] forState:UIControlStateNormal];
        [selectedBtn setImage:[UIImage imageNamed:@"Safety_selected"] forState:UIControlStateSelected];
        selectedBtn.tag = i + 10;
        [bgView2 addSubview:selectedBtn];
        [selectedBtn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(selectedBtn.right + 10, selectedBtn.top, width - 10 - 30 - 20, 30)];
        infoLabel.text = self.infoAry[i];
        infoLabel.textColor = [UIColor blackColor];
        infoLabel.font = FONT(15);
        infoLabel.adjustsFontSizeToFitWidth = YES;
        [bgView2 addSubview:infoLabel];
    
    }
    
    UIControl *firstBaseView = [bgView viewWithTag:1];
    self.scroll.contentSize = CGSizeMake(0, bgView2.bottom + 20);

    [self tapAction:firstBaseView];
    
}
- (void)tapAction:(UIControl *)sender {
    
    _selectedIndex = sender.tag - 1;
    
    for (int i = 1; i <= 3; i ++) {
        UIControl *baseView = [self.view viewWithTag:i];
        UIImageView *selectView = [baseView viewWithTag:10];
        if (sender.tag == i) {
            selectView.image = [UIImage imageNamed:@"Pay_selected"];
        } else {
            selectView.image = [UIImage imageNamed:@"Pay_unselected"];
        }
    }
    

}

- (void)selectAction:(UIButton *)btn{
    btn.selected = !btn.selected;
    
    if (btn.selected) {
        [self.infoSelect addObject:self.infoAry[btn.tag - 10]];
    }else{
        [self.infoSelect removeObject:self.infoAry[btn.tag - 10]];
    }
}

- (void)submit {
    
    __block BOOL canLoad = YES;
    
    [self.textFields enumerateObjectsUsingBlock:^(UITextField *tf, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (tf.text.length == 0) {
            
            canLoad = NO;
            *stop = YES;
        }
    }];
    
    if (!canLoad) {
        [ByCoreToolAlert showFailureWithText:@"请填写全部信息"];
        return;
    }
    
    NSMutableArray *images = [NSMutableArray new];
    [self.selectViews enumerateObjectsUsingBlock:^(ByViewBuySafetyCardSelect *view, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSLog(@"%ld",idx);
        if (view.image) {
            [images addObject:view.image];
        } else {
            if(idx == self.selectViews.count - 1){
                canLoad = YES;
            }else{
                canLoad = NO;
            }
            *stop = YES;
        }
    }];
    
    if (!canLoad) {
        [ByCoreToolAlert showFailureWithText:@"请上传必需证件照"];
        return;
    }
    
    [ByCoreToolAlert showLoadind:@"正在提交..." hasMasker:YES];
    [ByNetBaseApi uploadImages:images.copy type:@"other" success:^(NSArray<NSDictionary *> *success) {
        
        NSLog(@"%@", success);
        ByNetParamsModel *params = [ByNetParamsModel new];
        params.insurance_id = @"5";
        params.uid = BY_USER.uid;
        params.name = [self.textFields[0] text];
        params.car_code = [self.textFields[1] text];
        params.mobile = [self.textFields[2] text];
        params.id_front = success[0][@"id"];
        params.id_back = success[1][@"id"];
        params.driving_license_front = success[2][@"id"];
        params.driving_license_back = success[3][@"id"];
        params.annual_survey = success[4][@"id"];
        if (success.count == 6) {
           params.his_insurance = success[5][@"id"];
        }
        if (_selectedIndex == 0) {
            params.three_respons_insurance = @"50万";
        } else if (_selectedIndex == 1) {
            params.three_respons_insurance = @"100万";
        } else {
            params.three_respons_insurance = @"150万";
        }
        
        if (self.infoSelect.count != 0) {
            for (NSString *str in self.infoSelect) {
                params.three_respons_insurance = [params.three_respons_insurance stringByAppendingString:[NSString stringWithFormat:@",%@",str]];
            }
        }
        NSLog(@"%@",params.three_respons_insurance);

        [ByApiSafety applyAddCaySafety:params success:^(ByNetBaseResult *result) {
            
            [ByCoreToolAlert showSuccessWithText:result.msg];
            dispatch_after(dispatch_time(0, NSEC_PER_SEC * 2), dispatch_get_main_queue(), ^{
                [self dismissViewControllerAnimated:YES completion:nil];
            });
            
        } failure:^(ByNetBaseResult *result) {
            
            [ByCoreToolAlert showFailureWithText:result.msg];
        }];
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
        [ByCoreToolAlert showFailureWithText:error.domain];
        NSLog(@"error:%@", error.localizedDescription);
    }];
}
@end
